﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace WISD.Common
{
    public static class EFHelper
    {
        /// <summary>
        /// IList<T> 转换成 DataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(IList<T> list)
        {
            DataTable dt = new DataTable(typeof(T).Name);
            DataColumn column;
            DataRow row;
            System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
            {
                System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                string name = pi.Name;
                if (dt.Columns[name] == null)
                {
                    //column = new DataColumn(name, pi.PropertyType);
                    column = new DataColumn(name);
                    dt.Columns.Add(column);
                }
            }

            if (list == null || list.Count <= 0)
            {
                return dt;
            }
            else
            {
                foreach (T t in list)
                {
                    if (t == null)
                    {
                        continue;
                    }
                    row = dt.NewRow();
                    for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                    {
                        System.Reflection.PropertyInfo pi = myPropertyInfo[i];
                        string name = pi.Name;
                        row[name] = pi.GetValue(t, null);
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }
        }

    }
}
